package org.bluweb.g4wicket;

import java.util.HashMap;
import java.util.Map;

import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.template.JavaScriptTemplate;
import org.apache.wicket.util.template.PackagedTextTemplate;
import org.apache.wicket.util.template.TextTemplate;

@SuppressWarnings("serial")
public class G4WicketComponent extends Label implements IHeaderContributor {

	protected G4WicketComponent(String id) {
		super(id);
		this.setMarkupId(id);
		this.setOutputMarkupId( true );
	}

	@Override
	public void renderHead(IHeaderResponse response) {
		response.renderJavascriptReference( "http://www.google.com/jsapi" );
	}

	protected void setJavaScriptTemplate( String name, boolean includeTags ) {
		this.setJavaScriptTemplate( name, includeTags, null );
	}

	protected void setJavaScriptTemplate( String name, boolean includeTags, Map<String,Object> parameters ) {
		
		TextTemplate template = new PackagedTextTemplate(this.getClass(), name );
		if( includeTags ) {
			template = new JavaScriptTemplate( template );
		}
		
		String script;
		if( parameters == null ) {
			parameters = new HashMap<String,Object>();
		}

		parameters.put( "id", this.getId() );
		parameters.put( "markupid", this.getMarkupId() );
		
		script = template.asString( parameters );
		
		this.setDefaultModel( new Model<String>( script ) );
		this.setEscapeModelStrings( false );		
	}
	
	protected void execute( String script, G4WicketEvent event ) {

		event.getComponent().add(new AttributeAppender( event.getEvent(), new Model<String>( script ), ";"));		
	}	
}
